package com.powernode.auth2;

import com.powernode.service.UserService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 自定义授权模式：短信验证码模式
 */
public class SmsCodeTokenGranter extends AbstractTokenGranter {
    private UserService userService;

    public SmsCodeTokenGranter(AuthorizationServerTokenServices tokenServices,
                                  ClientDetailsService clientDetailsService,
                                  OAuth2RequestFactory requestFactory,
                                  UserService userService) {
        super(tokenServices, clientDetailsService, requestFactory, "sms_code");
        this.userService = userService;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        // 获取登录的请求参数
        Map<String, String> params = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        // 获取电话和验证码
        String mobile = params.get("mobile");
        String code = params.get("code");
        // 调用自定义获取用户信息的方法
        UserDetails userDetails = userService.loadUserByMobileAndCode(mobile, code);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                userDetails,null,userDetails.getAuthorities());

        authenticationToken.setDetails(params);

        OAuth2Request oAuth2Request = getRequestFactory().createOAuth2Request(client,tokenRequest);

        return new OAuth2Authentication(oAuth2Request,authenticationToken);
    }
}
